package com.nova.scenic.projectlibs.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.nova.scenic.projectlibs.util.debug.MyLog;
import com.nova.scenic.projectlibs.util.lifecyclehelper.LifeCycleHelper;
import com.nova.scenic.projectlibs.util.lifecyclehelper.LifeCycleHelperBase;
import com.nova.scenic.projectlibs.util.lifecyclehelper.LifeCycleLogHelper;

import java.io.FileDescriptor;
import java.io.PrintWriter;


public class BaseActivity extends AppCompatActivity {

    private static final String TAG = "BaseActivity";
    private LifeCycleHelper lifeCycleHelper = new InfernalCommonMessage(new InternalLifeCycleLog(null));


    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
        MyLog.i(TAG, "attachBaseContext " + newBase.getClass().getClassLoader());

    }

    @Override
    protected void onApplyThemeResource(Resources.Theme theme, int resid, boolean first) {
        super.onApplyThemeResource(theme, resid, first);


        if (lifeCycleHelper != null) {
            lifeCycleHelper.onApplyThemeResource(theme, resid, first);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onCreate(savedInstanceState);
        }
        MyLog.i(TAG, "class loader is " + getClassLoader() + getClassLoader().hashCode());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onDestroy();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onPause();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onStart();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onStop();
        }
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onRestart();
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onAttachedToWindow();
        }
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onDetachedFromWindow();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onNewIntent(intent);
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onRestoreInstanceState(savedInstanceState);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onTrimMemory(level);
        }

    }

    @Override
    public void finish() {
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onActivityFinish();
        }

        super.finish();

    }

    @Override
    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
        // 子类继承DebugUtil 重写dump时候方便直接使用
        DebugUtil.getInstance().updateContext(this);
        DebugUtil.getInstance().updateInputCmd(args);
        DebugUtil.getInstance().dump(prefix, fd, writer, args);
        if (lifeCycleHelper != null) {
            lifeCycleHelper.dump(prefix, fd, writer, args);
        }
    }

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        if (lifeCycleHelper != null) {
            lifeCycleHelper.onCreateView(parent, name, context, attrs);
        }
        return super.onCreateView(parent, name, context, attrs);
    }

    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
        if (lifeCycleHelper != null) {
            if (lifeCycleHelper.onGenericMotionEvent(event)) {
                return true;
            }
        }
        return super.onGenericMotionEvent(event);
    }

    @Override
    public boolean dispatchGenericMotionEvent(MotionEvent ev) {

        if (lifeCycleHelper != null) {
            if (lifeCycleHelper.dispatchGenericMotionEvent(ev)) {
                return true;
            }
        }


        return super.dispatchGenericMotionEvent(ev);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (lifeCycleHelper != null) {
            if (lifeCycleHelper.dispatchTouchEvent(ev)) {
                return true;
            }
        }


        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (lifeCycleHelper != null) {
            if (lifeCycleHelper.dispatchKeyEvent(event)) {
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (lifeCycleHelper != null) {
            if (lifeCycleHelper.onCreateOptionsMenu(menu)) {
                return true;
            }
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (lifeCycleHelper != null) {
            if (lifeCycleHelper.onOptionsItemSelected(item)) {
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    @Override
    protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
        super.onChildTitleChanged(childActivity, title);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    /////////////////////////////////////////////////生命周期结束///////////////////////////////////////////////////////////

    protected void requestLandscape() {
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    protected void requestFullScreen() {
        //去掉标题栏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉信息栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }


    protected void onNetworkChange(boolean connected) {

    }

    public String getName() {
        return this.getClass().getSimpleName() + "-" + this.hashCode() + " ";
    }

    protected LifeCycleHelper getLifeCycleHelper() {
        return lifeCycleHelper;
    }

    protected void setLifeCycleHelper(LifeCycleHelper lifeCycleHelper) {
        this.lifeCycleHelper = lifeCycleHelper;
    }




    /////////////////////////////////////////////////////

    private class InfernalCommonMessage extends LifeCycleHelperBase {

        public InfernalCommonMessage(LifeCycleHelper helper) {
            super(helper);
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            StringBuffer stringBuffer = new StringBuffer();

            // 获取应用程序最大可用内存
            int maxMemory = (int) Runtime.getRuntime().maxMemory();
            int cacheSize = maxMemory / 8;
            stringBuffer.append("the max memory of app can use is " + Formatter.formatFileSize(getApplicationContext(), maxMemory) + " cacheSize " + cacheSize)
                    .append("\n");

            DisplayMetrics outMetrics = new DisplayMetrics();
            getWindow().getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
            stringBuffer.append("density is " + outMetrics.density +
                    " densityDpi is " + outMetrics.densityDpi +
                    " width " + outMetrics.widthPixels +
                    " height " + outMetrics.heightPixels
            );

            long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

            stringBuffer.append("used is " + used);

//            WindowManagerGlobal.getInstance().startTrimMemory(TRIM_MEMORY_COMPLETE);

            Log.i(TAG, "InfernalCommonMessage " + stringBuffer.toString());
        }


    }



    private class InternalLifeCycleLog extends LifeCycleLogHelper {

        public InternalLifeCycleLog(LifeCycleHelper helper) {
            super(helper);
        }

        @Override
        public String getObjectInstance() {
            return "@" + MyLog.getInstanceName(BaseActivity.this);
        }
    }




}
